/// Creator:      gaoruishan
/// CreatDate:    2025-07-04
/// Description:  护嘱任务
Class Nur.MNISV3.Service.NurseTask Extends %RegisteredObject [ Not ProcedureBlock ]
{

/// 查询护嘱
/// w ##class(Nur.MNISV3.Service.NurseTask).GetNursingTaskDataV4("","2025-07-04","00:00","2025-07-04","23:59","3","20665","8","2","","{""single"":"""",""multiple"":""1"",""type"":""""}")
ClassMethod GetNursingTaskDataV4(episodeId, fromDate, fromTime, toDate, toTime, wardId, userId, locId, hospitalId, screenParts, extras) As %String
{
    n (episodeId, fromDate,fromTime, toDate,toTime, wardId, userId, locId, hospitalId,screenParts, extras,%session)
    s $zt="errGetNursingTaskDataV4"
    s ^GRS("GetNursingTaskDataV4")=$lb(episodeId, fromDate,fromTime, toDate,toTime, wardId, userId, locId, hospitalId,screenParts,  extras) 
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s extrasObj=##class(Nur.MNISV3.Common.JSON).Decode(extras)
    s type=extrasObj.GetAt("type")
    s screenPartsList=..getScreenPartsList(screenParts)
    s interventionItems=..GetInterventionItems(hospitalId)
    s patInfoList=##class(%ListOfDataTypes).%New()  
    i episodeId'="" {//单患者
        s patinfo=##class(%ArrayOfDataTypes).%New()
        //基本患者信息
        s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
        s nursingTaskData=##class(%ListOfDataTypes).%New() 
        s nursingTaskData=..GetNursingTaskData(episodeId,fromDate_" "_fromTime,toDate_" "_toTime,$g(temp("tStatus")),$g(type)) 
        d patinfo.SetAt($g(nursingTaskData),"nursingTaskData")
        d patInfoList.Insert(patinfo)
    }else {
        //调用纯净版患者列表，
        s patListObj=##class(%ResultSet).%New("Nur.MNISV3.Service.Patient:GetPatList")
        d patListObj.Execute(wardId,userId,"Ward",locId)
        while(patListObj.Next()){
            s patinfo=##class(Nur.MNISV3.Common.Utils).ResultSet(patListObj)
            s episodeId=patListObj.GetDataByName("episodeId")
            s nursingTaskData=..GetNursingTaskData(episodeId,fromDate_" "_fromTime,toDate_" "_toTime,$g(temp("tStatus")),$g(type)) 
            d patinfo.SetAt($g(nursingTaskData),"nursingTaskData")
            //基本患者信息
            s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
            d patInfoList.Insert(patinfo)
        }
    }
    ;;;撤销护嘱记录
    s IsOpenCancelNursePlan=##class(Nur.NIS.Service.NursingPlan.NursePlanMake).IsOpenCancelNursePlan(hospitalId)
    s slide=##class(%ArrayOfDataTypes).%New()
    s buttons=##class(%ListOfDataTypes).%New()
    d slide.SetAt(buttons,"buttons")
    i ($g(IsOpenCancelNursePlan)="Y") {
        s btn=##class(Nur.Tools).RapidAssembly("id,motion,text","undo","undo","撤销执行") 
        d buttons.Insert(btn)
    }
    i ($g(QPCCOpenDelNureTask)="Y") {
        s btn=##class(Nur.Tools).RapidAssembly("id,motion,text","delete","delete","删除") 
        d buttons.Insert(btn)
    }
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(screenPartsList),"screenParts") 
    d json.SetAt($g(interventionItems),"interventionItems") 
    d json.SetAt($g(slide),"slide")
    d json.SetAt($g(patInfoList),"patients") 
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetNursingTaskDataV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 获取详情
/// w ##class(Nur.MNISV3.Service.NurseTask).GetNursingTaskDetailV4("21||5||1||1","3","20665","8","2")
ClassMethod GetNursingTaskDetailV4(id, wardId, userId, locId, hospitalId)
{
    n (id,wardId, userId, locId, hospitalId,%session)
    s $zt="errGetNursingTaskDetailV4"
    s ^GRS("GetNursingTaskDetailV4")=$lb(id,wardId, userId, locId, hospitalId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s interventionItemId=..GetInterventionPropertyById(id,2)
    s obj=##class(Nur.NIS.Service.NursingPlan.TaskRecord).GetExecuteTaskList(id,interventionItemId,userId,hospitalId)
    s optionItems=obj.GetAt("result")
    s emrRecordId=obj.GetAt("emrRecordId")
    s executeDateTime=obj.GetAt("executeDateTime")
    s executeTemplate=obj.GetAt("executeTemplate")
    s executeUser=obj.GetAt("executeUser")
    s executedContent=obj.GetAt("executedContent")
    s resultObj=##class(%ResultSet).%New("Nur.NIS.Service.NursingPlan.EMRLinkItem:GetEMRLinkItemList")
    d resultObj.Execute("","",hospitalId)
    s NurEmrTemplateItems= ##class(Nur.Tools).ResultSetToList(resultObj)
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(optionItems),"optionItems")
    d json.SetAt($g(emrRecordId),"emrRecordId")
    d json.SetAt($g(executeDateTime),"executeDateTime")
    d json.SetAt($g(executeTemplate),"executeTemplate")
    d json.SetAt($g(executeUser),"executeUser")
    d json.SetAt($g(executedContent),"executedContent")
    d json.SetAt($g(NurEmrTemplateItems),"NurEmrTemplateItems")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetNursingTaskDetailV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 执行护嘱 
/// w ##class(Nur.MNISV3.Service.NurseTask).ExecuteNursingTaskV4("21||5||1||1","3","20665","8","2","execute","{""date"":""2025-07-11"",""transferFlag"":""1"",""options"":[{""itemId"":""1"",""itemValue"":""37"",""exeNoteList"":[]},{""itemId"":""2"",""itemValue"":"""",""childItemList"":[{""childId"":""2||1"",""childValue"":""""},{""childId"":""2||2"",""childValue"":""""}],""exeNoteList"":[]}],""nurseRecordEntryTplId"":""5"",""time"":""08:49"",""remarks"":""评估与高血压相关的因素，如家族史、生活习惯、职业等。""}")
ClassMethod ExecuteNursingTaskV4(id, wardId, userId, locId, hospitalId, motion, form)
{
    n (id, wardId, userId, locId, hospitalId,motion,form,%session)
    s $zt="errExecuteNursingTaskV4"
    s ^GRS("ExecuteNursingTaskV4")=$lb(id, wardId, userId, locId, hospitalId,motion,form)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s formObj= ##class(Nur.MNISV3.Common.JSON).Decode(form)
    s json=##class(%ArrayOfDataTypes).%New()
    i (motion="save") {//保存PRN任务
        s intRecordIds=formObj.GetAt("intRecordIds")
        s output=##class(Nur.NIS.Service.NursingPlan.TaskRecord).SavePRNTask(intRecordIds,wardId,userId)
        i output'=0 s Status="-1",Msg=output
    } elseif (motion="execute") {
        s interventionItemId=..GetInterventionPropertyById(id,2)
        s obj=##class(Nur.NIS.Service.NursingPlan.TaskRecord).GetExecuteTaskList(id,interventionItemId,userId,hospitalId )
        s content=obj.GetAt("executedContent")
        s optionItems=obj.GetAt("result")
        s options=formObj.GetAt("options")
        s date=formObj.GetAt("date")
        s time=formObj.GetAt("time")
        s remarks=formObj.GetAt("remarks")
        s records=..ParseOptions(optionItems,options)
        s admId=..GetAdmIdByPlanId(id)
        s NurRecId=..GetTaskPropertyById(id,30)
        s obj=##class(Nur.Tools).RapidAssembly( "episodeID,locID,userID,exedate,exetime,exeDesc,emrRecordId,record,exeDescFlag", admId,locId,userId,date,time,remarks,NurRecId,records,"true")
        s dataJson= ##class(Nur.MNISV3.Common.JSON).Encode(obj)
        s options= ##class(Nur.MNISV3.Common.JSON).Encode(options)
        s sessionJson=..GetSessionAsJson(locId,wardId,userId)
        s:$g(options)="" options="[]"
        s output= ##class(Nur.NIS.Service.NursingPlan.TaskRecord).ExecuteTask(userId,id,content,options,$g(transferFlag),locId,dataJson, hospitalId,sessionJson,$g(nurseRecordEntryTplId))
        i output'=0 s Status="-1",Msg=output
    } elseif (motion="undo") {
        s recordJson=..GetInputRecordAsJson(id)
        s output=##class(Nur.NIS.Service.NursingPlan.TaskRecord).CancelTaskRecord(userId,recordJson,1)
        i output'=0 s Status="-1",Msg=output
    } elseif (motion="delete") {
        s output=##class(Nur.NIS.Service.NursingPlan.TaskRecord).DelTaskRecord(userId,id)
        i output'=0 s Status="-1",Msg=output
    } elseif (motion="note") {
        s output=##class(Nur.NIS.Service.NursingPlan.TaskRecord).ExecuteNote(userId,id,$g(remarks))
        i output'=0 s Status="-1",Msg=output
    } elseif (motion="time") {
        s output=##class(Nur.NIS.Service.NursingPlan.TaskRecord).NurPlanTaskEditTime(id,$g(date),$g(time))
        i output'=0 s Status="-1",Msg=output
    }
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(Report),"Report")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errExecuteNursingTaskV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 查询PRN措施 
/// w ##class(Nur.MNISV3.Service.NurseTask).GetPrnInterventionsV4
ClassMethod GetPrnInterventionsV4(episodeId, wardId, userId, hospitalId)
{
    n (episodeId, wardId, userId, hospitalId,%session)
    s $zt="errGetPrnInterventionsV4"
    s ^GRS("GetPrnInterventionsV4")=$lb(episodeId, wardId, userId, hospitalId) 
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s resultObj=##class(%ResultSet).%New("Nur.NIS.Service.NursingPlan.TaskRecord:GetPrnInterventionList")
    d resultObj.Execute(episodeId,"",hospitalId)
    s prnInterventions= ##class(Nur.Tools).ResultSetToList(resultObj)
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(prnInterventions),"prnInterventions")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetPrnInterventionsV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

ClassMethod GetInputRecordAsJson(ids) As %String
{
    n (ids)
    s list=##class(%ListOfDataTypes).%New()
    s len=$l(ids,"^")
    f ind=1:1:len {
        s id=$p(ids,"^",ind)
        s NurRecId=..GetTaskPropertyById(id,30)
        s obj=##class(Nur.Tools).RapidAssembly("recordId^emrRecordId",id,NurRecId)
        d list.Insert(obj)
    }
    q ##class(Nur.MNISV3.Common.JSON).Encode(list)
}

ClassMethod ParseOptions(optionItems, options) As %String
{
    n (optionItems,options)
    k temp
    //w ##class(Nur.JSON).Encode(optionItems),!
    s len=options.Count()
    f ind=1:1:len {
        s option=options.GetAt(ind)
        s optionId=option.GetAt("itemId")
        s value=option.GetAt("itemValue")
        s temp(optionId)=value
        s children=option.GetAt("childItemList")
        i $isobject(children) {
            s len2=children.Count()
            f ind2=1:1:len2 {
                s option2=children.GetAt(ind2)
                s optionId2=option2.GetAt("childId")
                s value2=option2.GetAt("childValue")
                s temp(optionId,optionId2)=value2
            }
        }
    }
    s records=##class(%ListOfDataTypes).%New()
    s len=optionItems.Count()
    f ind=1:1:len {
        s optionItem=optionItems.GetAt(ind)
        s optionId=optionItem.GetAt("itemId")
        continue:('$d(temp(optionId)))
        s value=$g(temp(optionId))
        s children=optionItem.GetAt("data").GetAt("subItemList")
        s len2=children.Count()
        f ind2=1:1:len2 {
            s optionItem2=children.GetAt(ind2)
            s optionId2=optionItem2.GetAt("subItemId")
            continue:('$d(temp(optionId,optionId2)))
            s optionName2=optionItem2.GetAt("subItemName")
            s value=##class(Nur.Tools).Concat(value,",",optionName2)
            s value2=$g(temp(optionId,optionId2))
            s value=##class(Nur.Tools).Concat(value,",",value2)
        }
        s optionName=optionItem.GetAt("itemName")
        s optionName=$p($p($p(optionName,"("),"（"),".")
        s record=##class(Nur.Tools).RapidAssembly("id,name",optionId,optionName)
        d record.SetAt(value,"value")
        d records.Insert(record)
    }
    q records
}

ClassMethod GetAdmIdByPlanId(id) As %String
{
    n (id)
    s planId=$p(id,"||")
    s obj=##class(Nur.NIS.PlanRecord).%OpenId(planId)
    q:('$isobject(obj)) ""
    s admId=$s($isobject(obj.NPRECAdmDR):obj.NPRECAdmDR.%Id(),1:"")
    d obj.%Close()
    q admId
}

ClassMethod GetSessionAsJson(locId, wardId, userId, groupDesc = "住院护士") As %String [ Internal ]
{
    n (locId,wardId,userId,groupDesc,%session)
    s lgId=$s($d(%session): $g(%session.Data("LOGON.SSUSERLOGINID")),1:"")
    q "{""LOGON.CTLOCID"":"""_locId_
        """,""LOGON.WARDID"":"""_wardId_
        """,""LOGON.GROUPDESC"":"""_groupDesc_
        """,""LOGON.USERID"":"""_userId_
        """,""LOGON.SSUSERLOGINID"":"""_lgId_"""}"
}

ClassMethod GetTaskPropertyById(id, subscript) As %String
{
    q $p($g(^Nur.NIS.PlanRecord(+id,"Question",+$p(id,"||",2),"Intervention",+$p(id,"||",3),"Task",+$p(id,"||",4))),"^",subscript)
}

ClassMethod GetInterventionPropertyById(id, subscript) As %String
{
    q $p($g(^Nur.NIS.PlanRecord(+id,"Question",+$p(id,"||",2),"Intervention",+$p(id,"||",3))),"^",subscript)
}

/// w ##class(Nur.JSON).Encode(##class(Nur.MNISV3.Service.NurseTask).GetInterventionItems(2))
ClassMethod GetNursingTaskData(episodeIDString, dateFrom, dateTo, taskStatus, intType) As %String
{
    s resultObj=##class(%ResultSet).%New("Nur.NIS.Service.NursingPlan.TaskRecord:GetTaskList")
    d resultObj.Execute(episodeIDString, dateFrom, dateTo, taskStatus, intType)
    s List=##class(%ListOfDataTypes).%New()
    i '$IsObject(resultObj) q List
    while (resultObj.Next()){
        s obj=##class(%ArrayOfDataTypes).%New()
        f len=1:1:resultObj.GetColumnCount()
        {
             s ColumnName=resultObj.GetColumnName(len) 
             s Value=resultObj.GetDataByName(ColumnName)
             //返回的是 %ArrayOfDataTypes 转换对象
             i (Value["{")&&(Value["}") s Value=##class(Nur.JSON).Decode(Value)
             d obj.SetAt(Value,ColumnName)
        }
        s handlers=##class(%ListOfDataTypes).%New()
        s tStatus=obj.GetAt("tkStatusName")
        i (tStatus="未执行") {
            d handlers.Insert("delete")
        } 
        i (tStatus="已执行") {
            d handlers.Insert("undo")
            d handlers.Insert("delete")
        }
        d obj.SetAt(handlers,"handlers")
        d List.Insert(obj)
    }
    q List
}

/// w ##class(Nur.JSON).Encode(##class(Nur.MNISV3.Service.NurseTask).GetInterventionItems(2))
ClassMethod GetInterventionItems(hospId) As %String
{
    s resultObj=##class(%ResultSet).%New("Nur.NIS.Service.NursingPlan.InterventionSetting:FindInterventionType")
    d resultObj.Execute("",hospId)
    q ##class(Nur.Tools).ResultSetToList(resultObj)
}

/// w ##class(Nur.JSON).Encode(##class(Nur.MNISV3.Service.NurseTask).getScreenPartsList())
ClassMethod getScreenPartsList(screenParts)
{
      ;;;执行状态
    s TaskStatusJson=##class(Nur.NIS.Common.QueryBrokerNew).GetOptionOfProperty("Nur.NIS.TaskRecord","NTRECStatus")
    s list=##class(Nur.MNISV3.Common.JSON).Decode(TaskStatusJson)
    d ##class(Nur.Tools).ExtractFilterStr(screenParts,.temp) 
    s keyValue=""
    s len=list.Count()
    f ind=1:1:len {
        s item=list.GetAt(ind)
        s val1=item.GetAt("value")
        s val2=item.GetAt("text")
        i $g(temp("tStatus"))[val2 s temp("tStatus")=val1 //匹配上，赋值
        i keyValue="" s keyValue=val2
        e  s keyValue=keyValue_"!"_val2
    }
    s screenParts=##class(%ListOfDataTypes).%New()  
    s screenObj=##class(Nur.Tools).RapidAssembly("commonKey,keyCode,keyDesc,keyType,keyValue","true","tStatus","状态","Single",keyValue) 
    d screenParts.Insert(screenObj)
    // "keyValue": "未执行!已执行!已停止!已作废"
    q screenParts
}

}
